﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using Medianamik.Core.DAL.SQL.Clauses;

namespace Medianamik.Core.DAL.SQL
{
    public class FromClause : ISqlQueryPart
    {
        public ITable Table
        {
            get;
            private set;
        }

        private List<InnerJoin> _innerJoins; 
        public ReadOnlyCollection<InnerJoin>  InnerJoins
        {
            get
            {
                return _innerJoins.AsReadOnly();
            }
        }

        private List<CrossApplyClause> _crossApplies = new List<CrossApplyClause>();
        public List<CrossApplyClause> CrossApplies
        {
            get { return _crossApplies; }
        }

        public FromClause(ITable pTable)
        {
            Table = pTable;
            _innerJoins = new List<InnerJoin>();
        }

        public void InnerJoin(Column pForeignKeyTableColumn, Column pPrimaryKeyTableColumn)
        {
            _innerJoins.Add(new InnerJoin(pForeignKeyTableColumn,pPrimaryKeyTableColumn )); 
        }

        public void CrossApply(CrossApplyClause crossApplyClause)
        {
            CrossApplies.Add(crossApplyClause);
        }

        #region ISqlQueryPart Members


        public StringBuilder ToSQL()
        {
            var from = new StringBuilder(" FROM ")
                .Append("[" + Table.Schema + "].[" + Table.Name + "]")
                .Append( " " + Table.Alias  );
            foreach (var @join in InnerJoins)
            {
                from.Append(@join.ToSQL());
            }

            foreach (var crossApply in CrossApplies)
            {
                from.Append(crossApply.ToSQL());
            }

            return from;
                
        }

        #endregion
    }
}
